package com.sec.bnjey.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sec.bnjey.BaseActivity;
import com.sec.bnjey.R;
import com.sec.bnjey.bluetooth.BtService;
import com.sec.bnjey.bluetooth.BtUtil;
import com.sec.bnjey.bluetooth.OBDListener;
import com.sec.bnjey.global.GlobalApplication;
import com.sec.bnjey.global.RbPreference;
import com.sec.bnjey.network.HttpPost;
import com.sec.bnjey.network.NetworkEventListener;
import com.sec.bnjey.utils.RbLog;

public class RegDevSerialnoActivity extends BaseActivity implements
		OnClickListener, NetworkEventListener, OBDListener {

	private static final String TAG = "RegDevSerialnoActivity";

	EditText et_sn, et_phone, et_mileage;

	ArrayList<String> codeList2;
	String codes = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regdevserialnoactivity);

		RbLog.d(TAG, "onCreate");

		et_sn = (EditText) findViewById(R.id.SN_Edit);
		et_phone = (EditText) findViewById(R.id.SN_Edit2);
		et_mileage = (EditText) findViewById(R.id.SN_Edit3);

		viewInit();

		Toast.makeText(RegDevSerialnoActivity.this,
				"위 빈칸의 자동차 계기판 Km를 입력한 후 완료 버튼을 누르십시오.", Toast.LENGTH_LONG)
				.show();

		BtService.getBtService().OBD_Request(BtService.OBD_GET_SN_READ, null,
				RegDevSerialnoActivity.this);

	}

	/**
	 * get user's phone number
	 */
	private void viewSetMyPhoneNumber() {
		String mUserPhoneNumber = "";
		TelephonyManager telManager = (TelephonyManager) getApplicationContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		// org
		mUserPhoneNumber = removeCountryCode(telManager.getLine1Number());

		et_phone.setText(mUserPhoneNumber);
		et_phone.setEnabled(false);
	}

	/**
	 * 국가 코드 삭제한다.
	 * 
	 * @param countryCode
	 * @return
	 */
	private String removeCountryCode(String countryCode) {

		String newNumber = countryCode;

		if (countryCode == null || countryCode.equals(""))
			return null;

		if (countryCode.substring(0, 3).equals("+82")) {
			newNumber = countryCode.replace("+82", "0");
		}

		return newNumber;
	}

	private void viewInit() {

		TextView tv = (TextView) findViewById(R.id.TV_TopMenu_Title);
		tv.setText(" SN ,전화번호, Km 입력");

		Button b = (Button) findViewById(R.id.B_TopMenu_Left);
		b.setVisibility(View.GONE);

		b = (Button) findViewById(R.id.SN_Btn);
		b.setOnClickListener(this);

		EditText b2 = (EditText) findViewById(R.id.SN_Edit);
		b2.setPrivateImeOptions("defaultInputmode=english;");
		b2.setOnClickListener(this);
		viewSetMyPhoneNumber();
	}

	class OBDReadTask extends AsyncTask<Void, Void, Void> {
		byte[] OBD_SN;

		@Override
		protected Void doInBackground(Void... params) {
			OBD_SN = BtService.getBtService().OBD_SN_READ();

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			verifySN(OBD_SN);
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

	private void exitProgram() {
		BtService.getBtService().stop();
		GlobalApplication.stopBluetoothService();
		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		am.restartPackage(getPackageName());
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.B_TopMenu_Left:

			break;

		case R.id.SN_Btn:
			if (verifyValue()) {
				// do something more
				networkRequestUpdate();
			}
			break;
		}
	}

	private void networkRequestUpdate() {
		// update on network
		String mileage = et_mileage.getText().toString();
		String phone = et_phone.getText().toString();
		String sn = et_sn.getText().toString();

		// set mileage
		int numInt = Integer.parseInt(mileage);
		byte[] dis_byte = BtUtil.Int2Bytes(numInt * 10, 4);
		// obd에는 100m 단위로 들어가므로
		BtService.getBtService().OBD_REAL_MILEAGE(dis_byte);

		HttpPost.sendMileage(sn.toUpperCase(), phone, numInt, this);

	}

	private boolean verifyValue() {

		String mileage = et_mileage.getText().toString();
		String phone = et_phone.getText().toString();
		String sn = et_sn.getText().toString();

		// verify mileage
		if (mileage == null || mileage.length() == 0) {
			Toast.makeText(RegDevSerialnoActivity.this,
					"OBD와 통신이 되지 않습니다. 프로그램 종료후 다시 시작해주십시오.", Toast.LENGTH_LONG)
					.show();
			return false;
		}

		return true;
	}

	@Override
	public void onBackPressed() {

		InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		mgr.showSoftInput(this.getCurrentFocus(),
				InputMethodManager.SHOW_FORCED);
	}

	void RTC() {

		RbLog.d(TAG, "--- RTC ---");

		Date today = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(today);// 현재의 날짜를 받아온다

		Calendar cal2 = Calendar.getInstance();
		cal2.set(2012, 0, 1); // 기준이 되는 2012.0.1을 받아온다

		Calendar cal3 = Calendar.getInstance();
		cal3.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
				cal.get(Calendar.DATE));// 현재의 날짜를 년월일만 받아옴

		int count = 0;
		while (!cal2.after(cal3)) { // 기준날로 부터 현재까지의 일을 계산함(373)
			cal2.add(Calendar.DATE, 1);
			count++;
		}
		--count;

		int e = (count * 86400) + ((cal.get(Calendar.HOUR_OF_DAY)) * 3600)
				+ ((cal.get(Calendar.MINUTE)) * 60)
				+ (cal.get(Calendar.SECOND));
		byte[] t = BtUtil.Int2Bytes(e, 4);
		BtService.getBtService().OBD_RTC_TIME(t);
	}

	public boolean compare(byte[] a, byte[] b) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] != b[i]) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onNetworkEvent(int type, Object retObject) {

		RbLog.d(TAG, "onNetworkEvent " + type);

		String rspn = (String) retObject;

		switch (type) {
		case HttpPost.NETWORK_MILEAGE: {

			if (rspn == null || rspn.length() == 0)
				return;

			if (rspn.substring(11, 15).equals("true")) {

				RTC();
				RbPreference pref = new RbPreference(this);
				pref.update(RbPreference.PREF_SN, et_sn.getText().toString());
				pref.update(RbPreference.PREF_PHONE, et_phone.getText()
						.toString());

				overridePendingTransition(0, 0);
				finish();

			} else {
				Toast.makeText(
						RegDevSerialnoActivity.this,
						"서버와의 통신이 올바르지 않습니다. 휴대기기의 통신상태를 확인후 다시 시도해 주세요. 문제가 지속될 시 고객센터로 문의 주기기 바랍니다.\n< 1599 - 6236 >",
						Toast.LENGTH_LONG).show();

			}
			break;
		}
		}

	}

	@Override
	public void onOBDEvent(int type, Object retObject) {
		RbLog.d(TAG, "onOBDEvent");

		byte[] data = (byte[]) retObject;
		if (data == null) {
			RbLog.d(TAG, "onOBDEvent ret data is Null, Type:" + type);
		}

		switch (type) {
		case BtService.OBD_GET_COMMUNICATION_START:

			if (data != null && (data[0] == 4 || data[0] == 3 || data[0] == -1)) {
			} else {

			}
			break;

		case BtService.OBD_GET_SN_READ:
			verifySN(data);
			break;

		default:
			break;
		}

	}

	private void verifySN(byte[] data) {
		if (data == null || data.length == 0) {

			Toast.makeText(RegDevSerialnoActivity.this,
					"OBD장치와의 통신연결이 원활하지 않습니다. 다시 페어링 하신후 V-talk을 실행시켜주십시오.",
					Toast.LENGTH_LONG).show();

			Intent intent = new Intent();
			intent.putExtra("error_code", -1);
			setResult(RESULT_OK, intent);
			finish();

			BtService.getBtService().disconnect();

			return;
		} else {

			try {
				et_sn = (EditText) findViewById(R.id.SN_Edit);
				et_sn.setText(new String(data, "UTF-8"));
				et_sn.setEnabled(false);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void onDestroy() {
		hideSoftInput(et_mileage);
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		hideSoftInput(et_mileage);
		super.onPause();
	}

	// hide keyboard
	private void hideSoftInput(EditText editText) {
		InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}
}